package com.android.aiod.manager;

import android.content.Context;
import android.serialport.SerialPortFinder;

import com.android.aiod.bean.ConfigInfo;
import com.android.baselibrary.tool.CommToast;
import com.android.baselibrary.tool.Log;
import com.android.aiod.R;
import com.android.aiod.serialport.Device;
import com.android.aiod.serialport.SerialPortManager;
import com.blankj.utilcode.util.ToastUtils;
import com.licheedev.hwutils.ByteUtil;

public class SerialConnectManager {

    Context mContext;
    public Device mDevice;
    public String[] mDevices;

    private boolean mOpened = false;

    public SerialConnectManager(Context mContext) {
        this.mContext = mContext;

        initDevice();
    }


    /**
     * 初始化设备列表
     */
    private void initDevice() {
        SerialPortFinder serialPortFinder = new SerialPortFinder();
        // 设备
        mDevices = serialPortFinder.getAllDevicesPath();
//        if (mDevices.length == 0) {
//            CommToast.showToast(mContext, "找不到串口设备");
//        }
        String path = "";
        for (String str : mDevices) {
            path += str + ";";
            Log.i("str:" + str);
        }
//        CommToast.showToast(mContext, mDevices.length + "个串口设备:" + path);

    }

    /**
     * 打开或关闭串口
     */
    public void switchSerialPort(String path) {
        if (mOpened) {
            SerialPortManager.instance().close();
            mOpened = false;
        } else {
            // 波特率
            ConfigInfo configInfo = ConfigManager.instance().configInfo;
            mDevice = new Device(path, configInfo.baudrate+"");
            mOpened = SerialPortManager.instance().open(mDevice) != null;
            if (mOpened) {
                ToastUtils.showLong("打开串口成功");
            } else {
                ToastUtils.showLong("打开串口失败");
            }
        }
    }

    public void connectDefault() {
        switchSerialPort("/dev/ttyS0");
    }

    //发送数据
    public void sendData(String datas) {
        try {
            byte[] bytes = ByteUtil.hexStr2bytes(datas);
            SerialPortManager.instance().sendData(bytes);
        } catch (Exception e) {
            ToastUtils.showLong(e.getMessage());
            e.printStackTrace();
        }
    }

    //发送数据
    public void sendData(byte[] bytes) {
        try {
            SerialPortManager.instance().sendData(bytes);
//            ToastUtils.showLong("发送正应答成功");
        } catch (Exception e) {
//            ToastUtils.showLong("发送正应答失败");
            e.printStackTrace();
        }
    }

}
